package rhc.taskSchedule.taskSchedule.schedule.manage;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import rhc.taskSchedule.commander.TaskScheduleCommanderExecute;
import rhc.taskSchedule.entity.RunningStatus;
import rhc.taskSchedule.exception.RunningException;
import rhc.taskSchedule.taskDistribute.TaskDistribute;
import rhc.taskSchedule.taskSchedule.BasicManage;
import rhc.taskSchedule.taskSchedule.schedule.Schedule;
import rhc.taskSchedule.taskSchedule.schedule.TaskScheduleManage;
import rhc.taskSchedule.taskSchedule.schedule.schedule.TaskScheduleImpl;

abstract public class BasicTaskScheduleManageImpl extends BasicManage implements TaskScheduleManage {
	
	/**
	 * 任务分发器
	 */
	protected TaskScheduleCommanderExecute taskScheduleCommanderExecute;
	
	/**
	 * 运行id对应的调度执行器
	 */
	protected Map<String,Schedule> runningId_taskSchedule=new HashMap<String,Schedule>();
	
	/**
	 * 源id对应的运行id列表，一个任务或调度可能多次运行，也可能在同一个机器上多次运行
	 */
	protected Map<String,List<String>> sourceId_runningIdList=new HashMap<String,List<String>>();
	
	public BasicTaskScheduleManageImpl(TaskScheduleCommanderExecute TaskScheduleCommanderExecute){
		this.taskScheduleCommanderExecute=taskScheduleCommanderExecute;
	}
	
	@Override
	public List<String> getAllRunningId() throws Exception {
		return new LinkedList<String>(runningId_taskSchedule.keySet());
	}

	@Override
	public RunningStatus getRunStatus(String runningId) throws Exception {
		Schedule taskSchedule=getTaskScheduleByRunningId(runningId);
		
		return taskSchedule.getRunStatus();
	}

	@Override
	public void createRunning(String runningId) throws Exception {
		if(runningId_taskSchedule.containsKey(runningId)){
			throw new RunningException("调度 {} 已存在",runningId);
		}
		TaskDistribute taskDistribute=taskScheduleCommanderExecute.getTaskDistribute();
		Schedule taskSchedule=new TaskScheduleImpl(runningId,taskScheduleCommanderExecute);
		runningId_taskSchedule.put(runningId, taskSchedule);
		
		String taskId=taskSchedule.getSourceId();
		List<String> runningIdList=sourceId_runningIdList.get(runningId);
		if(null == runningIdList){
			runningIdList=new LinkedList<String>();
			sourceId_runningIdList.put(taskId, runningIdList);
		}
		runningIdList.add(runningId);
	}
	
	@Override
	public Schedule getTaskScheduleByRunningId(String runningId) throws Exception{
		Schedule taskSchedule=runningIdExists(runningId,true)?runningId_taskSchedule.get(runningId):null;
		
		return taskSchedule;
	}

	/**运行id是否存在
	 * @param runningId
	 * @return
	 */
	protected boolean runningIdExists(String runningId,boolean throwsException) throws Exception{
		Schedule taskSchedule=runningId_taskSchedule.get(runningId);
		if(null == taskSchedule && throwsException){
			throw new RunningException("运行 {} 在内存中不存在，可能已停止或未启动",runningId);
		}
		return null != taskSchedule;
	}
}
